"""Alertmanager helpers."""
from cki_lib import misc

EMOJI_SEVERITY = {
    'reminder': '⏰',
    'info': 'ℹ️',
    'warning': '⚠️',
    'important': '🔴',
    'serious': '🔥',
}


def _alert_emoji(alert):
    """Return alert emoji."""
    if alert['status'] == 'resolved':
        return '🔵'

    return EMOJI_SEVERITY.get(
        misc.get_nested_key(alert, 'labels/severity'), '🔴'
    )


def craft_notification(alerts, alertmanager_url, status):
    """Return notification message from alertmanager alerts list."""
    filtered = [a for a in alerts if a['status'] == status]
    if filtered:
        alert = filtered[0]
        what = alert['status'].upper()
        if len(filtered) > 1:
            what += f':{len(filtered)}'
        alert_name = alert['labels']['alertname']
        summary = alert['annotations']['summary']
        dashboard = alert['annotations'].get('dashboard', '')
        message = f'{_alert_emoji(alert)} [{what}] <{alertmanager_url}|{alert_name}>: {summary}'
        if dashboard:
            message += f' - <{dashboard}|dashboard>'

        return message

    return None
